<template>
  <div class="container">
    <div class="wrapper">
      <el-card class="box-card">
        <div slot="header" class="clearfix" style="text-align: center">
          <span style="font-size: 30px;color: #4ab344">注册</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="goLogin()">登录</el-button>
        </div>
        <div>
          <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form"
                   label-width="120px">
            <el-form-item prop="name" label="姓名">
              <el-input v-model="registerForm.name" type="text" auto-complete="off" placeholder="请输入姓名">
              </el-input>
            </el-form-item>
            <el-form-item prop="sex" label="性别">
              <el-radio v-model="registerForm.sex" label="0">男</el-radio>
              <el-radio v-model="registerForm.sex" label="1">女</el-radio>
            </el-form-item>
            <el-form-item prop="phone" label="手机号">
              <el-input v-model="registerForm.phone" type="text" auto-complete="off" placeholder="请输入手机号">
              </el-input>
            </el-form-item>
            <el-form-item prop="idCard" label="身份证号码">
              <el-input v-model="registerForm.idCard" type="text" auto-complete="off" placeholder="请输入身份证号码">
              </el-input>
            </el-form-item>
            <el-form-item prop="email" label="电子邮箱">
              <el-input v-model="registerForm.email" type="text" auto-complete="off" placeholder="请输入电子邮箱">
              </el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input
                  v-model="registerForm.password"
                  type="password"
                  auto-complete="off"
                  placeholder="请输入密码"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword" label="确认密码">
              <el-input
                  v-model="registerForm.confirmPassword"
                  type="password"
                  auto-complete="off"
                  placeholder="请输入确认密码"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaOnOff" label="验证码">
              <el-input
                  v-model="registerForm.code"
                  auto-complete="off"
                  placeholder="请输入验证码"
                  style="width: 63%"
              >
              </el-input>
              <div class="register-code">
                <img :src="codeUrl" @click="getCode" class="register-code-img"/>
              </div>
            </el-form-item>
          </el-form>
          <el-button
              :loading="loading"
              size="medium"
              type="success"
              style="width:100%;"
              @click="handleRegister"
          >
            <span v-if="!loading">注 册</span>
            <span v-else>注 册 中...</span>
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import {getCodeImg, register} from "@/utils/request";

export default {
  name: "Register",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    const checkPhone = (rule, value, callback) => {
      const reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/;
      if (!value) {
        return callback(new Error('请输入您的手机号'));
      }
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的手机号'));
        } else {
          callback();
        }
      }, 500);
    };
    const checkIdCard = (rule, value, callback) => {
      const reg = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if (!value) {
        return callback(new Error('请输入您的身份证号码'));
      }
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的身份证号码'));
        } else {
          callback();
        }
      }, 500);
    };
    const checkEmail = (rule, value, callback) => {
      const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/;
      if (!value) {
        return callback(new Error('请输入您的邮箱'));
      }
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的邮箱'));
        } else {
          callback();
        }
      }, 500);
    };
    return {
      codeUrl: "",
      registerForm: {
        phone: "",
        password: "",
        confirmPassword: "",
        code: "",
        uuid: "",
        sex: "",
        name: "",
        idCard: "",
        email: "",
      },
      registerRules: {
        name: [
          {required: true, trigger: "blur", message: "请输入您的姓名"}
        ],
        sex: [
          {required: true, trigger: "blur", message: "请选择您的性别"}
        ],
        idCard: [
          {required: true, validator: checkIdCard, trigger: 'blur'}
        ],
        phone: [
          {required: true, validator: checkPhone, trigger: 'blur'}
        ],
        email: [
          {required: false, validator: checkEmail, trigger: 'blur'}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"},
          {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, trigger: "blur", message: "请再次输入您的密码"},
          {required: true, validator: equalToPassword, trigger: "blur"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },

      loading: false,
      captchaOnOff: true
    };
  },
  methods: {
    //  跳转登录
    goLogin() {
      // 跳转页面
      this.$router.push({path: '/login'})
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.registerForm.uuid = res.uuid;
        }
      });
    },
    handleRegister() {
      this.$refs["registerForm"].validate(valid => {
        if (valid) {
          this.loading = true;
          register(this.registerForm).then(res => {
            const username = this.registerForm.phone;
            this.$alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", '系统提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              this.$router.push("/login");
            }).catch(() => {
              this.getCode();
            });
          }).catch(() => {
            this.loading = false;
            this.getCode();
          })
        }
      });
    }
  },
  created() {
    this.getCode();
  },
};
</script>

<style scoped lang="scss">
.container {
  height: 700px;
  width: 100%;
  background-color: #f4f4f4;
  padding: 1em 0;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 700px;
}

.wrapper {
  justify-content: center;
  align-items: center;
  display: flex;
}

.register-code-img {
  height: 38px;
}

.register-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
</style>
